package C8_4_ChangeReferenceToValue;

import java.util.Collection;
import java.util.Dictionary;
import java.util.Hashtable;
import java.util.Objects;

/**
 * Desc:&emsp;&ensp;将引用对象改为值对象
 * 必须先检查该对象是否可变，不可变则可以重构，否则不能使用本项重构
 * @author 李渊&emsp;
 * @version 1.0
 * @since V4.3&emsp;2022/7/13
 */
public class C8_4_demo {
    static class Cus{
        private final String name;

        public static final Cus create(String name){
            return new Cus(name);
        }

        public static final Cus getNamed(String name){
            return (Cus)_instances.get(name);
        }

        private Cus(String name) {
            this.name = name;
        }

        public String getName() {
            return name;
        }

        // 如何访问cus
        private static Dictionary _instances = new Hashtable();
        private void store(){
            _instances.put(this.getName(), this);
        }
        // 初始化一些cus
        static void loadCuss(){
            new Cus("A").store();
            new Cus("B").store();
            new Cus("C").store();
        }

        // 重写equals和hashcode
        @Override
        public boolean equals(Object arg){
            if(!(arg instanceof Cus)){
                return false;
            }
            return name.equals(((Cus) arg).getName());
        }

        @Override
        public int hashCode() {
            return Objects.hash(name);
        }
    }

    // 订单类
    class Order_2{
        // 客户
        private Cus _cus;

        public Order_2(String cusName) {
            this._cus = Cus.getNamed(cusName);
        }

        public String get_cus() {
            return _cus.getName();
        }

        public void set_cus(String cusName) {
            this._cus = Cus.getNamed(cusName);
        }
    }
}
